
	var associations = new Array();
	var exportMode = null;
	var data = null;
	
	function flip(id,element)
	{
		displayActions(false);
		
		if( element.checked )
		{
			document.getElementById("preview_"+id).className = "flip";
		}
		else
		{
			document.getElementById("preview_"+id).className = "";
		}
	}
	
	function getFormatSize(userFormat)
	{
		if ( formatsPixels[userFormat] )
		{
			return formatsPixels[userFormat];
		}
		else
		{
			return formatsPixels['A4'];
		}
	}
	
	function getFormatSizeInPt()
	{
		var convert = 2.83;
		var tab = new Array();
		for( var prop in allFormats )
		{
			tab[''+prop+''] = [ parseInt(allFormats[prop][0] * convert) , parseInt(allFormats[prop][1] * convert)];
			tab[''+prop.toLowerCase()+''] = [ parseInt(allFormats[prop][0] * convert) , parseInt(allFormats[prop][1] * convert)];
		}
		
		return tab;
	}
	
	function getFormatSizeInPixels()
	{
		var dpi = 135;
		var convert = dpi / 2.54 / 10;
		var tab = new Array();
		
		for( var prop in allFormats )
		{
			tab[''+prop.toLowerCase()+''] = [ parseInt(allFormats[prop][0] * convert) , parseInt(allFormats[prop][1] * convert)];
			tab[''+prop+''] = [ parseInt(allFormats[prop][0] * convert) , parseInt(allFormats[prop][1] * convert)];
		}
		return tab;
	}
	
	function getFormatLabelBySize(width, height, orientation)
	{
		var distX = 0;
		var distY = 0;
		
		for( var prop in formatsPixels )
		{
			if( orientation == 'portrait' )
			{
				distX = Math.abs(width - formatsPixels[prop][0]);
				distY = Math.abs(height - formatsPixels[prop][1]);
			}
			else
			{
				distX = Math.abs(width - formatsPixels[prop][1]);
				distY = Math.abs(height - formatsPixels[prop][0]);
			}
			
			if( distX < 10 && distY < 10 )
			{
				return prop;
			}
		}
		
		return 'a8';
	};
	
	function getAssocById(id)
	{
		var i = associations.length;
		var current = null;
		
		while( --i > -1 )
		{
			current = associations[i];
			if( current.id1 == id || current.id2 == id )
				return i;
		}
		
		return -1;
	}
	
	function cleanAssocById(id)
	{
		var srcId = -1;
		var targetId = -1;
		var srcSelect = null;
		var targetSelect = null;
		var srcCheckbox = null;
		var targetCheckbox = null;
		var srcFormat = null;
		var targetFormat = null;
		var srcPos = null;
		var targetPos = null;
		
		var index = getAssocById(id);
		var current  = null;
		
		while( index != -1 )
		{
			current = associations[index];
			srcId = current.id1;
			targetId = current.id2;
				
			srcSelect = document.getElementById('duo_'+srcId);
			targetSelect = document.getElementById('duo_'+targetId);
			srcCheckbox = document.getElementById('select_'+srcId);
			targetCheckbox = document.getElementById('select_'+targetId);
			
			if( srcSelect )
				srcSelect.value = -1;
			
			if( targetSelect )
				targetSelect.value = -1;
			
			if( targetCheckbox )
				targetCheckbox.checked = "";
				
			if( srcCheckbox )
				srcCheckbox.checked = "";
				
			associations.splice( index, 1 );
			
			index = getAssocById(id);
		}
	}

	function makeAssoc(srcId,targetId)
	{
		cleanAssocById(srcId);
		cleanAssocById(targetId);
		
		associations.push( {id1: srcId, id2: targetId} );
		
		var srcSelect = document.getElementById('duo_'+srcId);
		var targetSelect = document.getElementById('duo_'+targetId);
		
		var srcCheckbox = document.getElementById('select_'+srcId);
		var targetCheckbox = document.getElementById('select_'+targetId);
		
		var srcFormat = document.getElementById('frmt_'+srcId);
		var targetFormat = document.getElementById('frmt_'+targetId);
		
		var srcPos = document.getElementById('pos_'+srcId);
		var targetPos = document.getElementById('pos_'+targetId);
		
		if( targetPos && srcPos )
			targetPos.value = -parseInt(srcPos.value);
		
		if( targetFormat && srcFormat )
			targetFormat.value = srcFormat.value;
		
		if( srcSelect )
			srcSelect.value = targetId;
		
		if( targetSelect )
			targetSelect.value = srcId;
		
		if( targetCheckbox )
			targetCheckbox.checked = "checked";
			
		if( srcCheckbox )
			srcCheckbox.checked = "checked";
	}
	
	function assoc(id)
	{
		displayActions(false);
		var element = document.getElementById("duo_"+id);
		makeAssoc(parseInt(id),parseInt(element.value));
	}
	
	function eraseCookie(name) 
	{
		createCookie(name,"",-1);
	}
	
	function createCookie(name,value,days) 
	{
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function readCookie(name) 
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function deleteFiche(id)
	{
		var row = document.getElementById('line_'+id);
		var cookie = readCookie('printList');
		var list = (cookie == null ) ? new Array() : cookie.split(',');
		var i = list.length;
		var index = -2;
		
		removeFicheById(parseInt(id));
		
		if( row )
		{
			row.parentNode.removeChild(row);
		}
			
		while( --i > -1 )
		{
			if( list[i] == id )
				index = i;
		}
		
		if( index > -1 )
		{
			list.splice(index,2);
		}
		
		createCookie('printList',list.join(','));
	}
	
	function getFicheAfter(id)
	{
		var i = fiches.length;
		while( --i > -1 )
		{
			if( fiches[i].id == id )
			{
				if( i + 1 < fiches.length )
					return fiches[i+1];
			}
		}
		
		return null;
	}
	
	function getFicheById(id)
	{
		var i = fiches.length;
		while( --i > -1 )
		{
			if( fiches[i].id == id )
				return fiches[i];
		}
		
		return null;
	}
	
	function removeFicheById(id)
	{
		var results = new Array();
		var i = fiches.length;
		while( --i > -1 )
		{
			if( fiches[i].id == id )
				continue;
				
			results.push(fiches[i]);
		}
		
		fiches = results;
	};
	
	function displayActions(value)
	{
		var elements = document.getElementsByClassName("actionButtons");
		//var element = document.getElementById("swfContent");
		var element = null;
		var max = elements.length;
		var i = 0;
		
		for( i = 0; i < max; i++ )
		{
			element = elements[i];
			element.style.display = ( value == true ) ? "inline" :"none";
		}
	}
	
	function run(onlyId)
	{
		var i = fiches.length;
		var fiche = null;
		var printer = new Printer();
		var checkbox = null;
		var duo = null;
		var pos = null;
		var frmt = null;
		var reverse = null;
		var isPDF = document.getElementById('formatPDF').checked;
		var isPNG = document.getElementById('formatPNG').checked;
		var isJPG = document.getElementById('formatJPG').checked;
		var progress = document.getElementById('progress');
		var mode = ( isPNG ) ? 'png' : 'jpeg';
		
		displayActions(false);
		data = null;
		
		if( isPDF )
			mode = 'jpeg';
		
		printer.reset();
		
		while( --i > -1 )
		{
			fiche = fiches[i];
			
			checkbox = document.getElementById('select_'+fiche.id);
			reverse = document.getElementById('reverse_'+fiche.id);
			duo = document.getElementById('duo_'+fiche.id);
			pos = document.getElementById('pos_'+fiche.id);
			frmt = document.getElementById('frmt_'+fiche.id);
			
			duo = ( duo == null ) ? null : duo.value;
			pos = ( pos == null ) ? null : pos.value;
			
			if( onlyId != undefined )
			{
				if( fiche.id != onlyId )
				{
					checkbox.checked = null;
					checkbox.checked = false;
					continue;
				}
				else
				{
					checkbox.checked = "checked";
				}
			}
			
			if( checkbox.checked )
			{
				printer.addPrintJob(fiche,uiPath,reverse.checked,mode, duo, pos, frmt.value);
			}
		}
		
		progress.innerText = "0%";
		printer.addEventListener(tomahawk_ns.Event.PROGRESS, this, _progressHandler);
		printer.addEventListener(tomahawk_ns.Event.COMPLETE, this, _completeHandler);
		printer.print();
	}
	
	function _progressHandler(event)
	{
		var printer = event.target;
		var progress = document.getElementById('progress');
		progress.innerText = parseInt(printer.getProgression()*100)+"%";
	}
	
	function _completeHandler(event)
	{
		var progress = document.getElementById('progress');
		var printer = event.target;
		progress.innerText = "100%";
		data = printer;
		
		displayActions(true);
	}
	
	function saveList(only)
	{
		exportMode = 'save';
		if( isPDF() == true )
			exportPDF(data,only);
		else
			exportRAW(data,only);
	}
	
	function printList(only)
	{
		exportMode = 'print';
		if( isPDF() == true )
		{
			noPrintPDF();
			//exportPDF(data);
		}
		else
		{
			exportRAW(data,only);
		}
	}
	
	
	function noPrintPDF()
	{
		alert("pdf files cannot be print");
	}
	
	function noPngForPDF()
	{
		alert("The pdf format does'nt support png, please rebuild while selecting pdf or jpeg mode");
	}
	
	function isPDF()
	{
		var isPDF = document.getElementById('formatPDF').checked;
		return ( isPDF == true );
	}
	
	function getExport()
	{
		//return null;
		var exports = data.getExport();
		var i = exports.length;
		var currentExport = null;
		var obj = null;
		var tab = new Array();
		
		while( --i > -1 )
		{
			currentExport = exports[i];
			obj = new Object();
			obj.imgData = currentExport.image.src;
			obj.width = currentExport.image.width;
			obj.height = currentExport.image.height;
			obj.name = currentExport.name+'.'+currentExport.mode;
			tab.push(obj);
		}
		
		return tab;
	}
	
	function exportPDF(printer, only)
	{
		var doc = null;
		var data = null;
		var image = null;
		var width = 0;
		var height = 0;
		var exports = printer.getExport();
		var i = exports.length;
		var currentExport = null;
		var size = null;
		var fiche = null;
		var link = '';
		var format = null;
		var isLandscape = false;
		var currentName = "";
		
		while( --i > -1 )
		{
			currentExport = exports[i];
			
			if( currentExport.mode == "png" )
			{
				noPngForPDF();
				return;
			}
			
			fiche = currentExport.fiche;
			image = currentExport.image;
			currentName = currentExport.name;
			orientation = (fiche.isLandscape == true) ? 'landscape' : 'portrait';
			
			if( only != undefined )
			{
				if( fiche.id != only )
					continue;
			}
			
			if( currentExport.duo != null && currentExport.duo > -1 )
			{
				orientation = ( orientation == 'portrait' ) ? 'landscape' : 'portrait'; 
			}
			
			format = getFormatLabelBySize(image.width,image.height, orientation);
			doc = new jsPDF(orientation,"mm",format, false, formatsInPt);
			width = doc.internal.pageSize.width;
			height = doc.internal.pageSize.height
			
			data = image.src.slice('data:image/jpeg;base64,'.length);
			data = atob(data);
			size = getFormatSizeInPt(fiche.format);
		
			doc.addImage(data, 'JPEG', 0, 0, width, height);
			doc.save(currentName+'.pdf');
		}
		
	}
	
	function exportRAW(printer, only)
	{
		var image = null;
		var exports = printer.getExport();
		var i = exports.length;
		var currentExport = null;
		var w = null;
		var data = "";
		var canvas = document.createElement("canvas");
		var context = canvas.getContext("2d");
		var isSave = exportMode == 'save';
		var specs = null;
		var fiche = null;
		
		while( --i > -1 )
		{
			currentExport = exports[i];
			image = currentExport.image;
			fiche = currentExport.fiche;
			
			if( only != undefined )
			{
				if( fiche.id != only )
					continue;
			}
			
			if( isSave == true )
			{
				canvas.width = image.width;
				canvas.height = image.height;
				context.drawImage(image,0,0);
				
				if( swfContent.swfSaveData )
				{
					swfContent.swfSaveData(image.src);
				}
				else
				{
					canvas.toBlob(function(blob) {
						saveAs(
							  blob
							, currentExport.name+"."+currentExport.mode
						);
					}, "image/"+currentExport.mode);
				}
			}
			else
			{
				w = window.open(image.src,'_blank', 'width='+image.width+',height='+image.height+",left="+(i*20)+'');
			}
			
		}
	}
	
	function trace()
	{
		console.log(arguments);
	}
	
    window.onload = function()
    {
        Tomahawk.run();
		init();
    };
	
	